
import { mapGetters } from "vuex";

import "_p/basic/assets/js/softPhone/swfobject.js"
import "_p/basic/assets/js/softPhone/base64.js"
import "_p/basic/assets/js/softPhone/web_socket.js"
import "_p/basic/assets/js/softPhone/json2.js"
import "_p/basic/assets/js/softPhone/mycomm.agent.js"

import { querySoftPhoneParams, addApproveTele ,voiceHandlerOne} from "@/projects/afs-core-business/api/afs-case/soft-phone/softPhone";

console.log(_AFS_PROJECT_CONFIG)

export default {
    data() {
        return {
            // 废弃地址从工程配置处获取参数  _AFS_PROJECT_CONFIG.softPhone 就是软电话地址配置 api为api地址 ws为websocket地址
            // interfaceURL: "http://10.50.130.235:8080/gwaf/IService", //CCS接口地址
            // ctiServer: "demo1.mycommipcc.cn:17010", //CTI服务器
            agentId: "a1933", //坐席ID
            agentName: "ccqc03", //坐席名称
            password: "ccqc!29)", //密码
            queue: 'sales,support,sk5933', //技能组
            orgId: 'demo1.mycommipcc.cn', //组织ID
            workId: '3001933', //工号
            isLeader: true, //是否为班长坐席
            agentType: ['cc'], //坐席类型 cc:>呼叫坐席 wx:>微信坐席 wc:>webchat坐席
            softPhone: null, // 软电话实例
            queues: [], //当前组织ID的所有技能组名
            agents: [], //所有坐席
            appNo :  '',
            cusName :  '',
            cusPhone :  '',
            code:'',//返回的会话ID
            voiceId:'',
            // userInfo: {}, //用户信息
        }
    },
    computed: {
        ...mapGetters({ sysUserInfo: "userInfo" }),
    },
    methods: {
        // 请求
        // 初始化
        init() {
            let softPhone;
            //创建座席实例对象，后续可以直接使用该对象的所有对外属性、方法和回调函数（事件）
            softPhone = new MyCommAgent();

            softPhone.on_login_s = this.loginSuccess
            softPhone.on_login_f = this.loginFail
            softPhone.on_state_change = this.stateChange
            softPhone.on_dial_s = this.dialSuccess
            softPhone.on_dial_f = this.dialFail
            softPhone.on_call_agent_s = this.callAgentSuccess
            softPhone.on_call_agent_f = this.callAgentFail
            softPhone.on_logout_s = this.logoutSuccess
            softPhone.on_logout_f = this.logoutFail
            softPhone.on_get_queues_s = this.getQueuesSuccess
            softPhone.on_get_all_agents_s = this.getAllAgentsSuccess
            softPhone.on_agent_dialout_succ = this.ageentDialoutSuccess //外呼成功
            softPhone.on_agent_dialout_fail = this.ageentDialoutFail //外呼失败
            // softPhone.on_agent_service_start = this.agentServiceStart //来电接听
            softPhone.on_agent_service_end = this.agentServiceEnd //挂断
            softPhone.on_agent_ext_hangup = this.agentExtHangup //坐席挂断

            this.softPhone = softPhone;
            console.log(this.softPhone);
        },
        // 登录
        login() {
            console.log('userInfo', this.sysUserInfo);
            let params = {
                staffid: this.$store.state.user.userInfo.username

            }
            querySoftPhoneParams(params).then(res => {
                if (res.code === "0000" && res.data) {
                    this.agentId = res.data.cti_NO; //坐席ID
                    this.agentName = res.data.agent_NAME; //坐席名称
                    let password = '1234'; //密码
                    let queue = 'sales'; //技能组
                    let orgId = 'default'; //组织ID
                    let workId = res.data.cti_NO; //工号
                    let isLeader = false; //是否为班长坐席
                    let agentType = ['cc']; //坐席类型 cc=>呼叫坐席 wx=>微信坐席 wc=>webchat坐席
                    this.softPhone.login(this.agentId, password, queue, isLeader, orgId, this.agentName, workId, agentType);
                } else {
                    this.$Message.error('初始化失败,未检索到用户相关信息.');
                }

            })

        },
        //设置客户端
        setClient() {
            // if ($("#CallNumber").length) {
            //     client = 'ics'
            // } else {
            //     client = 'acs'
            // }
        },
        /**
         * 示闲
         */
        clickSetIdle() {
            this.softPhone.waiting();
            // currentCallId = 0;
        },
        /**
         * 示忙
         */
        clickSetBusy() {
            this.softPhone.idle();
        },
        /**
         * 应答
         */
        answer() {
            // alert('请从SIP客户端中接听')
            this.$Message.info('请从SIP客户端中接听')
        },
        /**
         *点击挂机按钮
         */
        clickHangup() {
            this.softPhone.drop();
        },

        //呼出
        clickCallOut(type, callee, applicationno, borrower) {
            if (!type) return;
            let appNo, cusName, cusPhone; //申请号,客户姓名,客户电话
            appNo = applicationno || '';
            cusName = borrower || '';

            this.cusPhone=callee || '';
            // if (loginStatus == 0) {
            //     alert("请先登录！");
            //     if ($("[data-bind=PHONE]") != undefined) {
            //         $("[data-bind=PHONE]").next().find("#callout").removeAttr("disabled");
            //         $("[data-bind=PHONE]").next().find("#callout2").removeAttr("disabled");
            //         $("[data-bind=PHONEC]").next().find("#callout2").removeAttr("disabled");
            //         $("[data-bind=PHONEC]").next().find("#callout").removeAttr("disabled");
            //     }
            //     return;
            // }
            // if (type == "1") {
            //     // var callee = $.trim($("#softPhoneNumber").val());
            //     cusPhone = callee;
            // }
            // if (callee == undefined || callee.length == 0) {
            //     alert("未输入呼出号码");
            //     return;
            // }
            // // if (isNaN(callee)) {
            // // 	alert("呼出号码应为数字");
            // // 	return;
            // // }
            // // var callMode = callee.length <= 9 ? 1 : 0 //0=>外呼 1=>内拨
            var callMode = 0; //业务只有外呼
            // $("#btnCallOut").addClass("Shover");
            // $("#btnCallOut").attr("disabled", true);
            // console.log("callMode->" + callMode);
            // console.log(callee, queues)
            // // 区别内拨和外呼的接口
            console.log('this.softPhone.dial', this.cusPhone);
            if (callMode == 0) {
                this.softPhone.dial(this.cusPhone, this.queues.join(), 'suiludata') //外拨号码，技能组，随路数据
            } else {
                this.softPhone.call_agent(callee) //agentid
            }

        },
        //保持
        Hold() {
            this.softPhone.hold();
        },
        //取保持
        setRetrieveHold() {
            this.softPhone.unhold();
        },
        //取消
        cannel() {
            this.softPhone.drop();
        },

        //调用咨询功能
        doConsultation(callNum) {
            // 做兼容处理 ICS从CallNumber取值 ACS从softPhoneNumber取值
            // var callNum = $.trim($("#CallNumber").val() || $("#softPhoneNumber").val());
            // if (callNum.length == 0) {
            //     alert('请输入咨询号码!')
            //     return;
            // }
            var callMode = callNum.length <= 9 ? 1 : 0 //0=>外呼 1=>内拨
            if (callMode == 0) {
                this.softPhone.consult(callNum);
            } else {
                this.softPhone.consult_agent(callNum);
            }

        },

        // 取消咨询
        reConnect() {
            this.softPhone.cancel_consult();
        },
        // 结束咨询
        stopConnect() {
            this.softPhone.stop_consult();
        },

        //会议功能 todo 三方会议添加成员
        doSingleStepConfCall(callee) {
            Hold();
            // var callee = $.trim($("#softPhoneNumber").val());
            var callMode = callee.length <= 6 ? 1 : 0 //0=>外呼 1=>内拨
            // 区别内拨和外呼的接口
            if (callMode == 0) {
                this.softPhone.dial(callee, queues.join(), 'suiludata') //外拨号码，技能组，随路数据
            } else {
                this.softPhone.call_agent(callee) //agentid
            }
        },

        /**
         * 注销
         */
        clickSignOut() {
            this.softPhone.logout();
        },

        /**
         * 外拨接听
         */
        ageentDialoutSuccess(evt) {
            console.log('外拨接听成功', evt)
            // currentCallId = evt.params.call_uuid
            console.log("ev"+evt.params.call_uuid)
            console.log("voice"+this.voiceId)
            //外拨成功 保存业务数据
            let paramsTwo={
                code:"ANSWER",  //ANSWER:客户接听
                voiceId: this.voiceId,
                callId:evt.params.call_uuid,
            }
            voiceHandlerOne(paramsTwo).then(res =>{
                if (res.code === "0000" && res.data) {

                }
            })


            const { call_uuid, callee_number, caller_number, queue, user_data } = evt.params;
            let params = {
                callId: call_uuid,
                phone: callee_number,
                queue,
                userName: this.agentName,
                userId: this.agentId

            };

            // call_uuid: "b27a4b4e-dbcb-11ea-9c7b-a32fb3f3437d"
            // callee_number: "18173939703"
            // caller_number: "1933"
            // queue: "sales,1,0,0,0,sk5933,1,0,0,0,support,1,0,0,0"
            // user_data: "suiludata"

            // this.currentCall = evt.params

            // voiceHandler('ANSWER')
            //  * 通话记录唯一标识 String callId;
            //  * 坐席id String userId;
            //  * 坐席姓名 String userName;
            //  * 与申请人关系 String custRelation;
            //  * 客户id  Long custId;
            //  * 客户姓名 String custName;
            //  * 申请编号 String applyNo;
            //  * 电话 String phone;
            //  * 录音文件ID;录音/文本 Long recordId;
            //  * 录音文本 String recordText;
            //  * 拨出时间 Date callTime;
            //  * 通讯时长（秒） BigDecimal communicatTime;
            //  * 结束时间 Date endTime;

            addApproveTele(Object.assign({}, this.phoneParams, params)).then(res => {
                console.log('外拨传给后台数据：', res);
                if (res.code === "0000" && res.data) {

                }
            })
            // 拨号成功后清空数据
            this.updatePhoneParams({})
        },

        ageentDialoutFail(evt) {
            console.log(evt, '外拨失败')
        },

        //内部呼叫成功 todo
        onCallInsideSuccTalk() {
            //如果是会议按钮触发的内呼执行成功则开启会议功能
            if (currentOPT == 'MEETING') {
                //与指定坐席呼叫成功，获取保持的电话的callId
                // WebAgent.invoker("GetCallID", [1],  (callId) {
                // 	//启动三方通话
                // 	WebAgent.invoker("Conference", [callId],  (returnValue) {

                // 	});
                // });
            }
        },

        /**
         * 外呼通话建立事件 todo
         */
        OnCallOutsideSuccTalk() {
            if (currentOPT == 'MEETING') {
                //与指定坐席呼叫成功，获取保持的电话的callId
                // WebAgent.invoker("GetCallID", [1],  (callId) {
                // 	//启动三方通话
                // 	WebAgent.invoker("Conference", [callId],  (returnValue) {

                // 	});
                // });
            }
        },

        OnConsultationFailure() {
            console.log("ConsultationFailure");
        },
        /**
         * 咨询成功
         */
        OnConsultationSuccess() {
            console.log("OnConsultationSuccess");

            // if (currentOPT == 'TRANSFER') {
            //     $('#btnTransfer').val('完成');
            //     $('#btnTransfer').unbind("click");
            //     $("#btnTransfer").one("click", Transfer);
            // }
        },

        Transfer(phone) {
            this.softPhone.transfer(phone, false);
        },

        /*******************/
        // 回调
        loginSuccess(evt) {
            this.softPhone.get_queues(); //获取当前组织ID的所有技能组名
            this.softPhone.get_all_agents()
            // throw new Error('component must implement loginSuccess method')
            this.v_loginSuccess(evt)
        },
        loginFail() {
            throw new Error('component must implement loginFail method')
        },

        alertError(evt, remark) {
            // var remark = remark || '失败'
            // var desc = (evt.params && evt.params.err_desc) || '未知'
            // var code = (evt.params && evt.params.err_num) || '未知'
            // addMessages(remark + ',原因:' + desc + '  错误码:' + code)
            // alert(remark + ',原因:' + desc + '  错误码:' + code)
        },

        dialSuccess(evt) {
            console.log('拨号成功', evt);
            // var direct = "CX_BAS_CHANNEL_DIR_OUTBOUND"; //呼叫方向呼出
            // var caller_number = ctiNum; // displayNum
            // var callee_number = cusPhone;
            // $.ajax({
            //     url: interfaceURL + "/voiceHandler.do", //请求的URL
            //     timeout: 3000, //超时时间设置，单位毫秒
            //     type: 'post', //请求方式，get或post
            //     data: {
            //         "code": "RING",
            //         "direct": direct,
            //         "caller": caller_number,
            //         "callee": callee_number,
            //         "staffId": userStaffid,
            //         "uintId": unitId,
            //         "agentName": username,
            //         "callId": '-',
            //         "app_no": app_no,
            //         "cusName": cusName
            //     },
            //     async: false,
            //     dataType: 'text', //返回的数据格式
            //     success: (data) { //请求成功的回调函数
            //         console.log("voiceId:" + data);
            //         currentVoiceId = data;
            //     },
            //     complete: (XMLHttpRequest, status) { //请求完成后最终执行参数
            //     }
            // });
            // $("[data-bind=PHONE]").next().find("#callout").removeAttr("disabled");
            // $("[data-bind=PHONE]").next().find("#callout2").removeAttr("disabled");
            // $("[data-bind=PHONEC]").next().find("#callout2").removeAttr("disabled");
            // $("[data-bind=PHONEC]").next().find("#callout").removeAttr("disabled");
            //外拨成功 保存业务数据
            let paramsOne={
                code:"RING",  //RING:呼叫振铃
                direct:"CX_BAS_CHANNEL_DIR_OUTBOUND",
                caller:this.agentId,
                callee:  this.cusPhone,
                /*staffId:this.$store.state.user.userInfo.username,*/
                staffId:'fanyansheng',
                uintId:"Collection",
                agentName:this.agentName,
                callId:"-",
                app_no:this.appNo,
                cusName:this.cusName
            }

            voiceHandlerOne(paramsOne).then(res =>{
                if (res.code === "0000" && res.data) {
                    this.voiceId=res.data
                    console.log("返回voce"+res.data)
                }
            })
        },

        dialFail(evt) {
            console.log('拨号失败', evt);
            // alertError(evt, '拨号失败')
            this.$Message.error('拨号失败')
        },
        // 挂断
        agentServiceEnd(evt) {
            console.log('挂断', evt);
            //挂断
            let paramsThree={
                code:"HANDUP",  //HANGUP:挂断电话
                voiceId:this.voiceId

            }
            voiceHandlerOne(paramsThree).then(res =>{
                if (res.code === "0000" && res.data) {

                }
            })
        },

        callAgentSuccess() {
            console.log('内拨成功')
        },

        callAgentFail(evt) {
            console.log('内拨失败', evt)

            // alertError(evt, '内拨失败')
        },

        logoutSuccess() {
            this.$Message.success("签出成功!");

            // $("#phonestatus").addClass("background", "#ec3333");
            // location.reload();
        },

        agentExtHangup(evt) {
            console.log('坐席挂机', evt)
            // voiceHandler("HANDUP");
            //挂断
            let paramsThree={
                code:"HANDUP",  //HANGUP:挂断电话
                voiceId:this.voiceId

            }
            voiceHandlerOne(paramsThree).then(res =>{
                if (res.code === "0000" && res.data) {

                }
            })
        },

        logoutFail(evt) {
            console.log('签出失败', evt);
            // console.log(evt);
            // alertError(evt, '签出失败')
        },
        //
        getQueuesSuccess(evt) {
            console.log('getQueuesSuccess', evt);
            if (evt && evt.params)
                this.queues = evt.params.queues;
        },

        getAllAgentsSuccess(evt) {
            console.log('获取所有坐席成功', evt)
            if (evt && evt.agents)
                this.queues = evt.params.agents;
        },

        addMessages(msg) {
            // $("#messages").html(msg)

        },

        stateChange(state) {
            var stateName = state.params.state_name
            var stateId = state.params.state_id
            var obj = {
                'st_logged_out': '签出',
                'st_pending': '未决',
                'st_on_break': '小休',
                'st_idle': '忙碌',
                // 'st_idle': '空闲',
                'st_waiting': '空闲',
                // 'st_waiting': '就绪',
                'st_offering': '队列来电', // 请求服务
                'st_incoming_call': '分机来电',
                'st_in_queue_call': '队列来电通话',
                'st_in_inbound_call': '分机来电通话中',
                'st_dialing': '外拨呼叫分机',
                'st_dialing_out': '外拨呼叫用户',
                'st_in_outbound_call': '呼出通话中',
                'st_transferring': '转移中',
                'st_transferring_wait': '转移等待返回',
                'st_holding': '保持',
                'st_pre_consult': '咨询准备',
                'st_consult_canceling': '咨询取消中',
                'st_consulting': '咨询中',
                'st_consult_stopping': '咨询停止中',
                'st_three_way': '三方',
                'st_three_way_stopping': '三方停止中',
                'st_pre_eavesdrop': '监听准备',
                'st_eavesdropping': '监听中',
                'st_pre_intercept': '拦截准备',
                'st_intercepting': '拦截中',
                'st_incoming_innercall': '内呼被叫中',
                'st_in_innercall': '内听通话中',
                'st_outgoing_innercall': '内呼呼出中',
                'st_inserting': '强插通话中',
                'st_pre_secret_talk': '密语准备',
                'st_secret_talking': '密语中',
                'st_wait_preview': '等待预览',
                'st_previewing': '预览中',
                'st_wrap_up': '完成',
                "st_post_call": '话后'
            }
            var cname = obj[stateName] || '其他';
            var ename = stateName
            // $("#state").val(cname)
            this.refreshBtns(stateId)
            // currentStat = stateId;
            console.log(state, 'on stateChange:', ename, cname);
            this.$Message.info("状态切换至[" + cname + "]");

        }

    }
}
